package com.cloud.cloudshop.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cloud.cloudshop.shop.constant.Constants;
import com.cloud.cloudshop.shop.dao.OrderMessageDao;
import com.cloud.common.entity.OrderMessageEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class RabbitmqTemplateConfig {

	@Autowired
	private OrderMessageDao orderMessageDao;

	@Bean
	public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
		RabbitTemplate template = new RabbitTemplate(connectionFactory);
		template.setMandatory(true);
		//确保消息成功发送到rabbitmq , confirm模式
		template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
			@Override
			public void confirm(CorrelationData correlationData, boolean ack, String cause) {
				log.info("correlationData: " + correlationData + "ack:" + ack);
				String messageId = correlationData.getId();
				if (ack) {
					log.info("----消息被确认ack:"+correlationData);
					log.info("----消息被确认cause:"+cause);
					//如果confirm返回成功 则进行更新
					OrderMessageEntity orderEntity = new OrderMessageEntity();
					orderEntity.setId(messageId);
					orderEntity.setStatus(Constants.ORDER_SEND_SUCCESS);

					UpdateWrapper<OrderMessageEntity> updateWrapper = new UpdateWrapper<>();
					updateWrapper.eq("message_id",messageId);
					orderMessageDao.update(orderEntity,updateWrapper);
				} else {
					//失败则进行具体的后续操作:重试 或者补偿等手段
					log.error("异常处理..."+correlationData);
					log.error("异常处理...cause:"+cause);
				}
			}
		});

		template.setReturnCallback(new RabbitTemplate.ReturnCallback() {
			@Override
			public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

				log.info("-----消息路由失败");
				log.info("-----message:"+ JSON.toJSONString(message));
				log.info("-----replyCode:"+ replyCode);
				log.info("-----replyText:"+ replyText);
				log.info("-----exchange:"+ exchange);
				log.info("-----routingKey:"+ routingKey);
			}
		});

		return template;
	}


}